package com.hmall.search.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.mapper.SearchMapper;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestDTO;
import com.hmall.search.service.ISearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

@Service
public class SearchService extends ServiceImpl<SearchMapper, Item> implements ISearchService {


    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * feign远程调用
     */
    @Autowired
    ItemClient itemClient;

    @Override
    public PageDTO search(RequestDTO requestDTO) throws IOException {

        //获取索引库hmall对象
        SearchRequest request = new SearchRequest("hmall");
        //新建复合查询 bool查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //搜索框输入的值 如果输入了就去分词查  没输入就查全部
        if (requestDTO.getKey() == null || requestDTO.getKey().equals("")){
            //must 必须查 参与算分
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.matchQuery("all",requestDTO.getKey()));
        }
        //根据品牌查
        if (requestDTO.getBrand()!=null){
            //过滤  filter必须查询 但不参与算分
            boolQuery.filter(QueryBuilders.termQuery("brand",requestDTO.getBrand()));
        }
        //根据分类查
        if (requestDTO.getCategory()!=null){
            //过滤  filter必须查询 但不参与算分
            boolQuery.filter(QueryBuilders.termQuery("category",requestDTO.getCategory()));
        }
        //根据价格区间查
        if (requestDTO.getMaxPrice()!=null && requestDTO.getMinPrice()!=null){
            //range 精确查询的一种 查在某值与某值区间 多用于价格 时间 另一种是term
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(requestDTO.getMinPrice()).lte(requestDTO.getMaxPrice()));
        }
        //执行复合查询
        request.source().query(boolQuery);


        //分页   从多少条数据开始(from)查多少条(size)数据
        request.source().from((requestDTO.getPage()-1)*requestDTO.getSize()).size(requestDTO.getSize());

        //高亮
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

        //排序 销量 价格
        //根据销量排序 sold
        if (requestDTO.getSortBy().equals("sold")){
            request.source().sort("sold",SortOrder.DESC);
            //根据价格排序 price
        }else if (requestDTO.getSortBy().equals("price")){
            request.source().sort("price", SortOrder.ASC);
        }

        //广告 算分
        //functionScoreQuery是在查询里 所以先放之前的查询结果 然后根据查询结果的算分给指定数据加权
        FunctionScoreQueryBuilder isAD = QueryBuilders.functionScoreQuery(
                boolQuery,//这里是之前的复合查询
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //精确查询到isAD字段为true的字段加权 1000倍
                                QueryBuilders.termQuery("isAD",true),
                                ScoreFunctionBuilders.weightFactorFunction(1000)
                        )
                }
        );
        //执行加权
        request.source().query(isAD);
        //发送请求
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        //解析数据并返回
        SearchHits hits = search.getHits();
        //返回的结果里hits里有total 和数据集合，高亮hits
        SearchHit[] hits1 = hits.getHits();
        ArrayList<ItemDoc> itemDocs = new ArrayList<>();
        for (SearchHit documentFields : hits1) {
            //获取hits里的每一条数据
            String hitsItem = documentFields.getSourceAsString();
            //把字符串反序列化封装为ItemDoc对象存入集合
            ItemDoc itemDoc = JSON.parseObject(hitsItem, ItemDoc.class);
//            //高亮返回
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
            if (highlightFields!=null&&highlightFields.size()>0){
                HighlightField name = highlightFields.get("name");
                String string = name.getFragments()[0].string();
                itemDoc.setName(string);
            }
            itemDocs.add(itemDoc);
        }
        return new PageDTO(hits.getTotalHits().value,itemDocs);
    }

    @Override
    public void deleteItemById(Long id) {


        DeleteRequest request = new DeleteRequest("hmall",id.toString());
        try {
            restHighLevelClient.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveItemById(Long id) {
        try {
        Item item = itemClient.getById(id);
        IndexRequest request = new IndexRequest("hmall").id(id.toString());
            ItemDoc itemDoc = new ItemDoc(item);
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            restHighLevelClient.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
